{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\Anaconda\\envs\\zju\\lib\\site-packages\\sklearn\\neural_network\\_multilayer_perceptron.py:691: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (500) reached and the optimization hasn't converged yet.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Confusion Matrix:\n",
      "[[19  0  0]\n",
      " [ 0 12  1]\n",
      " [ 0  0 13]]\n",
      "\n",
      "Classification Report:\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       1.00      1.00      1.00        19\n",
      "           1       1.00      0.92      0.96        13\n",
      "           2       0.93      1.00      0.96        13\n",
      "\n",
      "    accuracy                           0.98        45\n",
      "   macro avg       0.98      0.97      0.97        45\n",
      "weighted avg       0.98      0.98      0.98        45\n",
      "\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'pd' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[1], line 42\u001b[0m\n\u001b[0;32m     39\u001b[0m \u001b[38;5;28mprint\u001b[39m(classification_report(y_test, y_pred))\n\u001b[0;32m     41\u001b[0m \u001b[38;5;66;03m# 创建一个DataFrame来展示模型的系数\u001b[39;00m\n\u001b[1;32m---> 42\u001b[0m mlp_coef \u001b[38;5;241m=\u001b[39m \u001b[43mpd\u001b[49m\u001b[38;5;241m.\u001b[39mDataFrame(mlp\u001b[38;5;241m.\u001b[39mcoefs_, columns\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mLayer_\u001b[39m\u001b[38;5;124m'\u001b[39m \u001b[38;5;241m+\u001b[39m \u001b[38;5;28mstr\u001b[39m(i\u001b[38;5;241m+\u001b[39m\u001b[38;5;241m2\u001b[39m) \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(mlp\u001b[38;5;241m.\u001b[39mn_layers_ \u001b[38;5;241m-\u001b[39m \u001b[38;5;241m1\u001b[39m)], index\u001b[38;5;241m=\u001b[39miris\u001b[38;5;241m.\u001b[39mfeature_names)\n\u001b[0;32m     43\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124mModel Coefficients:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m     44\u001b[0m \u001b[38;5;28mprint\u001b[39m(mlp_coef)\n",
      "\u001b[1;31mNameError\u001b[0m: name 'pd' is not defined"
     ]
    },
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m在当前单元格或上一个单元格中执行代码时 Kernel 崩溃。\n",
      "\u001b[1;31m请查看单元格中的代码，以确定故障的可能原因。\n",
      "\u001b[1;31m单击<a href='https://aka.ms/vscodeJupyterKernelCrash'>此处</a>了解详细信息。\n",
      "\u001b[1;31m有关更多详细信息，请查看 Jupyter <a href='command:jupyter.viewOutput'>log</a>。"
     ]
    }
   ],
   "source": [
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neural_network import MLPClassifier\n",
    "from sklearn.metrics import classification_report, confusion_matrix\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "import pandas as pd\n",
    "\n",
    "# 加载鸢尾花数据集\n",
    "iris = load_iris()\n",
    "X = iris.data\n",
    "y = iris.target\n",
    "\n",
    "# 划分数据集为训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
    "\n",
    "# 数据标准化\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "# 创建MLP分类器实例\n",
    "mlp = MLPClassifier(hidden_layer_sizes=(5,), # 一个隐藏层，5个神经元\n",
    "                      activation='relu',      # 激活函数使用ReLU\n",
    "                      solver='adam',           # 优化算法使用Adam\n",
    "                      max_iter=500,            # 最大迭代次数\n",
    "                      random_state=42)\n",
    "\n",
    "# 训练模型\n",
    "mlp.fit(X_train_scaled, y_train)\n",
    "\n",
    "# 预测测试集\n",
    "y_pred = mlp.predict(X_test_scaled)\n",
    "\n",
    "# 输出混淆矩阵和分类报告\n",
    "print(\"Confusion Matrix:\")\n",
    "print(confusion_matrix(y_test, y_pred))\n",
    "\n",
    "print(\"\\nClassification Report:\")\n",
    "print(classification_report(y_test, y_pred))\n",
    "\n",
    "# 创建一个DataFrame来展示模型的系数\n",
    "mlp_coef = pd.DataFrame(mlp.coefs_, columns=['Layer_' + str(i+2) for i in range(mlp.n_layers_ - 1)], index=iris.feature_names)\n",
    "print(\"\\nModel Coefficients:\")\n",
    "print(mlp_coef)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
